package blue.blog.file;

import java.io.File;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.blue.core.file.IFileHandler;

import blue.blog.core.service.CmsDocFileService;

@Component
public class PicFileHandler implements IFileHandler
{
	private static final String THUMB = "thumb";
	
	@Value("${crawler.root}")
	private String root;
	
	@Resource
	private CmsDocFileService cmsDocFileService;
	
	public PicFileHandler()
	{
	}

	@Override
	public boolean accept(File file)
	{
		if (file.isFile())
			return true;
		
		if (file.isDirectory() && file.getPath().contains(THUMB))
			return false;
		
		return true;
	}

	@Override
	public void handle(File file)
	{
		String path = file.getPath();
		path = path.replaceAll("\\\\", "/");
		
		if (path.startsWith(root))
		{
			path = path.substring(root.length());
		}
		
		boolean exist = cmsDocFileService.existPath(path);
		//System.out.printf("%s 是否存在：%s\n", file.getAbsolutePath(), exist);
		if (exist)
			return;
		
		System.out.println(file.getAbsolutePath() + " 不存在，需要删除");
		this.delete(file, path);
	}
	
	private void delete(File file, String path)
	{
		File thumb = getThumb(file);
		
		if (file.exists())
		{
			FileUtils.deleteQuietly(file);
			System.out.println("删除：" + file);
		}
		if (thumb.exists())
		{
			FileUtils.deleteQuietly(thumb);
			System.out.println("删除：" + thumb);
		}
		
	}
	
	private File getThumb(File file)
	{
		String pathPic = file.getAbsolutePath();
		int pos = pathPic.lastIndexOf(File.separatorChar);
		String path = pathPic.substring(0, pos);
		String fileName = pathPic.substring(pos);
		String thumb = path + File.separator + THUMB + fileName;
		
		return new File(thumb);
	}
	
}
